package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * @author tang
 * @data 2021/9/6
 * @apiNode
 */
@Service
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;

    @Override
    public PageResult getItemList(PageResult pageResult) {
        Page<Item> itemPage = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        itemQueryWrapper.like(flag, "title", pageResult.getQuery());
        itemPage = itemMapper.selectPage(itemPage,itemQueryWrapper);
        pageResult.setTotal(itemPage.getTotal()).setRows(itemPage.getRecords());
        return pageResult;
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void deleteItemById(Item item) {
        String local = "G:/images";
        Item item1 = getById(item.getId());
        String path = item1.getImages();
        String[] split = path.split(",");
        for (String virtualPath : split) {
            String localPath = local + virtualPath;
            File file = new File(localPath);
            if (file.exists()){
                file.delete();
            }
        }
        itemMapper.deleteById(item.getId());
        itemDescMapper.deleteById(item.getId());

    }

    @Override
    public Item getById(Integer id) {
        return itemMapper.selectById(id);
    }

    @Override
    @Transactional
    public void updateItem(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        //item  主键自增  数据库入库之后  才会有主键
        Item item = itemVO.getItem();

        item.setStatus(true);
        itemMapper.insert(item);
        //itemDesc的id和item的id一样
        ItemDesc itemDesc = itemVO.getItemDesc();
        /**
         * mybatis实现业务功能,自动回显主键
         * MP自动的将主键的回显功能实现
         */
        itemDesc.setId(item.getId());  //MP自动的将主键的回显功能实现,所以item入库之后自动回显了id，所以可以直接取到item的id

        itemDescMapper.insert(itemDesc);
    }
}
